package webpage;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;

public class AddRemoveFriend {
	
	public String addFriend(String loginEmail,String emailaddress){
		String path = "C:/SVN/WebContent/Members/"+emailaddress+"/pendingrequests.txt";
		String result = "Couldn't send friend request";
		PrintWriter out;
		try {
			out = new PrintWriter(new BufferedWriter(new FileWriter(path, true)));
			out.println(loginEmail);
			out.close();
			result= "Friend request sent.";
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println(result);
		return result;
	    
	    
	}
public String removeFriend(String loginEmail,String emailaddress){
	String path1 = "C:/SVN/WebContent/Members/"+loginEmail+"/friends.txt";
	String path2 = "C:/SVN/WebContent/Members/"+emailaddress+"/friends.txt";
	String result = "Couldn't remove from friends.";
	try {
		File file = new File(path1);
		File temp = File.createTempFile("file", ".txt", file.getParentFile());
		String charset = "UTF-8";
		String delete = emailaddress;
		BufferedReader reader = new BufferedReader(new FileReader(file));
		PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(temp), charset));
		for (String line; (line = reader.readLine()) != null;) {
			line = line.replace(delete, "");
			writer.println(line);
			System.out.println(line);
		}
		reader.close();
		writer.close();
		file.delete();
		temp.renameTo(file);
		temp.delete();
		
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	try {
		File file = new File(path2);
		File temp = File.createTempFile("file", ".txt", file.getParentFile());
		String charset = "UTF-8";
		String delete = loginEmail;
		BufferedReader reader = new BufferedReader(new FileReader(file));
		PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(temp), charset));
		for (String line; (line = reader.readLine()) != null;) {
			line = line.replace(delete, "");
			writer.println(line);
			System.out.println(line);
		}
		reader.close();
		writer.close();
		file.delete();
		temp.renameTo(file);
		temp.delete();
		result = "Successfully removed from friends.";
		
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	System.out.println(result);
	return result;
		
}

}

